#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main() {
    for(;;) {
        int sockfd;
        struct sockaddr_in addr;
        
        // 1. 创建套接字
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0) {
            perror("socket creation failed");
            return -1;
        }
        
        // 2. 设置服务器地址
        bzero(&addr, sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_port = htons(1080);
        if (inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr) <= 0) {
            perror("invalid address");
            close(sockfd);
            return -1;
        }
        
        // 3. 连接服务器
        if (connect(sockfd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
            perror("connection failed");
            close(sockfd);
            continue;  // 连接失败后继续尝试
        }
        
        // 4. 用户交互
        printf("input message (or 'quit' to exit):\n");
        char buff[1024] = {0};
        if (fgets(buff, sizeof(buff), stdin) == NULL) {
            perror("input error");
            close(sockfd);
            continue;
        }
        
        // 去除换行符
        buff[strcspn(buff, "\n")] = 0;
        
        // 5. 检查是否退出
        if (strcmp(buff, "quit") == 0) {
            close(sockfd);
            break;
        }
        
        // 6. 发送数据
        if (write(sockfd, buff, strlen(buff)) < 0) {
            perror("write failed");
            close(sockfd);
            continue;
        }
        
        // 7. 接收响应
        bzero(buff, sizeof(buff));
        ssize_t n = read(sockfd, buff, sizeof(buff)-1);
        if (n < 0) {
            perror("read failed");
        } else if (n == 0) {
            printf("server closed connection\n");
        } else {
            printf("received from server: %s\n", buff);
        }
        
        // 8. 关闭连接
        close(sockfd);
    }
    
    return 0;
}